package com.chatai.repository;

import com.chatai.model.ChatMessage;
import com.chatai.model.ChatRoom;
import com.chatai.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface ChatMessageRepository extends JpaRepository<ChatMessage, Long> {
    // 根据聊天室查找消息，按时间倒序
    List<ChatMessage> findByChatRoomOrderByTimestampDesc(ChatRoom chatRoom);
    
    // 根据聊天室和发送者查找消息
    List<ChatMessage> findByChatRoomAndSenderOrderByTimestampDesc(ChatRoom chatRoom, User sender);
    
    // 查找聊天室的最新消息
    @Query("SELECT m FROM ChatMessage m WHERE m.chatRoom = :chatRoom ORDER BY m.timestamp DESC LIMIT 1")
    ChatMessage findLatestByChatRoom(@Param("chatRoom") ChatRoom chatRoom);
    
    // 原有方法保留
    List<ChatMessage> findBySenderType(String senderType);
    List<ChatMessage> findByIsAIResponse(boolean isAIResponse);
    List<ChatMessage> findAllByOrderByTimestampAsc();
}